package com.woniu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.woniu.config.AlipayConfig;
import com.woniu.config.RabbitMQConfig;
import com.woniu.entity.FlowerOrder;
import com.woniu.service.FlowerOrderService;
import com.woniu.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Api(value = "支付接口", tags = "支付功能")
public class AlipayController {
    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayTradePagePayRequest alipayRequest;

    @Resource
    private AlipayConfig alipayConfig;

    @Resource
    private FlowerOrderService fos;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/query")
    @ApiOperation("查询支付状态")
    public R query(String orderId) throws AlipayApiException {
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderId + "\"}");

        //请求
        AlipayTradeQueryResponse execute = alipayClient.execute(alipayRequest);

        String code = execute.getCode();
        Date sendPayDate = execute.getSendPayDate();
        if ("10000".equals(code) && sendPayDate != null) {
            String outTradeNo = execute.getOutTradeNo();
            String tradeNo = execute.getTradeNo();
            FlowerOrder order = new FlowerOrder();
            order.setOrderId(Long.valueOf(outTradeNo));
            order.setTradeNo(tradeNo);
            order.setStatus((byte) 2);
            order.setUpdateTime(new Date());
            Integer update = fos.updateOrderByOrderId(order);
            if (update > 0) {
                return R.success("已支付，正在前往订单页面");
            } else {
                return R.error("失败");
            }
        } else {
            return R.build(900, "尚未支付", null);
        }
    }

    @RequestMapping("/pay")
    @ApiOperation("进行支付")
    public String pay(String orderId, String total, String name, String body) throws AlipayApiException {
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderId + "\","
                + "\"total_amount\":\"" + total + "\","
                + "\"subject\":\"" + name + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("得到的结果：\n" + result);

        //加入延时队列
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.NORMAL_EXCHANGE_NAME,
                RabbitMQConfig.NORMAL_ROUTING_KEY,
                orderId);
        System.out.println("已加入延时队列");

        return result;
    }

    @RequestMapping("/returnUrl")
    @ApiOperation("支付完成后的操作")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            String result = "提示：trade_no:" + trade_no + "<br/>out_trade_no:" + out_trade_no + "<br/>total_amount:" + total_amount;

            FlowerOrder order = new FlowerOrder();
            order.setOrderId(Long.valueOf(out_trade_no));
            order.setTradeNo(trade_no);
            order.setStatus((byte) 2);
            order.setUpdateTime(new Date());
            Integer update = fos.updateOrderByOrderId(order);
            if (update > 0) {
                response.sendRedirect("http://localhost:8040/#/order");
            }
        }
    }
}
